<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery1">
        <a-row :gutter="24">
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <a-form-item label="状态">
              <!-- 状态：0已保存 1已提交（已返货） 2已签收 3已签收待确认 4已确认 -->
              <a-select v-model="queryParam.bizStatus" allowClear>
                <a-select-option value="1">待签收</a-select-option>
                <a-select-option value="2">已签收</a-select-option>
                <a-select-option value="3">待确认</a-select-option>
                <a-select-option value="4">已确认</a-select-option>
              </a-select>
            </a-form-item>
          </a-col> 
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <a-form-item label="门店">
              <a-cascader
                :options="departModel.departTreeOptions"
                :showSearch="true"
                expand-trigger="hover"
                placeholder=""
                :fieldNames="departModel.fieldNames"
                style="width: 180px"
                v-model="queryParam.selecteddeparts"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <a-form-item label="sku编码">
              <a-input placeholder="" v-model.trim="queryParam.itemSku" allowClear></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <a-form-item label="单据号">
              <a-input placeholder="" v-model.trim="queryParam.billNo" allowClear></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item>
              <template #label>
                <a-select v-model="queryParam.dateColumn">
                  <a-select-option value="applyTime">申请时间</a-select-option>
                  <a-select-option value="signTime">签收时间</a-select-option>
                </a-select>
              </template>
              <a-range-picker
                :ranges="{ 今天: [moment(), moment()], 近7天:[moment().subtract(7, 'days'),moment()],本月: [moment().startOf('month'), moment().endOf('month')] }"
                v-model="orderDateRange"
                @change="handleChange"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery1" icon="search">查询</a-button>
              <a-button type="default" @click="searchReset1" icon="reload" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button type="primary" icon="download" @click="handleExportXls1('收银单')" :loading="exportLoading">导出Excel</a-button>
    </div>

    <!-- table区域-begin -->
    <div>
      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        class="j-table-force-nowrap"
        @change="handleTableChange"
      >
        <span slot="action" slot-scope="text, record">
          <a @click="handleDetail(record)">详情</a>
        </span>
        <!--状态：0已保存 1已提交（已返货） 2已签收 3已签收待确认 4已确认 -->
        <span slot="bizStatus" slot-scope="text">
          <a-tag color="orange" v-if="text === 1">待签收</a-tag>
          <a-tag color="green" v-if="text === 2">已签收</a-tag>
          <a-tag color="blue" v-if="text === 3">待确认</a-tag>
          <a-tag color="cyan" v-if="text === 4">已确认</a-tag>
          <a-tag v-if="text === -1">已作废</a-tag>
        </span>
      </a-table>
    </div>
    <!-- table区域-end -->

    <!-- 表单区域 -->
    <posStockReturnBill-modal ref="modalForm" @ok="modalFormOk"></posStockReturnBill-modal>
  </a-card>
</template>

<script>
import '@/assets/less/TableExpand.less'
import PosStockReturnBillModal from './modules/PosStockReturnBillModal'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import moment from 'moment'
import { queryDepartTreeList1 } from '@/api/api'
import {downloadFile} from '@/api/manage'

export default {
  name: 'PosStockReturnBillList',
  mixins: [JeecgListMixin],
  components: {
    PosStockReturnBillModal,
  },
  data() {
    return {
      description: '返货单管理页面',
      disableMixinCreated: true,
      orgList: [],
      orderDateRange: [],
      model: {},
      moment,
      auditVisible: false,
      auditConfirmLoading: false,
      exportLoading: false,
      validatorRules1: {
        bizStatus: [{ required: true, message: '必填项' }],
        remark: [{ required: true, message: '必填项' }],
      },
      departModel: {
        departTreeOptions: [],
        fieldNames: { label: 'title', value: 'value', children: 'children' },
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      // 表头
      columns: [
        {
          title: '单据号',
          align: 'center',
          dataIndex: 'billNo',
        },
        {
          title: '所属机构',
          align: 'center',
          dataIndex: 'orgName',
        },
        {
          title: '返货门店',
          align: 'center',
          dataIndex: 'shopName',
        },
        {
          title: '总数量',
          align: 'center',
          dataIndex: 'totalQty',
          customRender:(text,record)=>{
            if(record.bizStatus === 3 || record.bizStatus === 4){
              return record.adjustTotalQty
            }else{
              return text
            }
          }
        },
        {
          title: '总金额(元)',
          align: 'center',
          dataIndex: 'totalAmount',
          customRender:(text,record)=>{
            if(record.bizStatus === 3 || record.bizStatus === 4){
              return record.adjustTotalAmount
            }else{
              return text
            }
          }
        },
        {
          title: '申请人',
          align: 'center',
          dataIndex: 'clerkUserName',
        },
        {
          title: '申请时间',
          align: 'center',
          dataIndex: 'bizDate',
        },
        {
          title: '单据状态',
          align: 'center',
          dataIndex: 'bizStatus',
          scopedSlots: { customRender: 'bizStatus' },
        },
        {
          title: '签收时间',
          align: 'center',
          dataIndex: 'signDate',
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' },
        },
      ],
      url: {
        list: '/stock/posStockReturnBill/list',
        exportBatchUrl: '/stock/posStockReturnBill/exportBatch'
      },
    }
  },
  computed: {},
  created() {
    this.$set(this.queryParam, 'bizStatus', '1')
    this.$set(this.queryParam, 'dateColumn', 'applyTime')
    this.loadDepartTree()
    this.searchQuery1()
  },
  methods: {
    checkExportParam() {
      let limit = 1000
      if (this.dataSource.length > limit) {
        this.$message.warning('单此导出最多支持'+ limit +'个单据')
        return false
      }

      return true
    },
    async handleExportXls1(fileName) {
      if (!this.checkExportParam()) {
        return
      }
      this.exportLoading = true
      let dateStr = moment().format('YYYYMMDD')
      await downloadFile(this.url.exportBatchUrl,'返货单'+ dateStr +'.zip', this.queryParam)
      this.exportLoading = false
    },
    assembleQueryParam() {
      console.log(this.queryParam.selecteddeparts)
      let selecteddeparts = this.queryParam.selecteddeparts
      if (selecteddeparts && selecteddeparts.length == 2) {
        this.queryParam.orgIds = selecteddeparts[0]
        this.queryParam.shopIds = selecteddeparts[1] == 0 ? null : selecteddeparts[1]
      } else {
        this.queryParam.orgIds = null
        this.queryParam.shopIds = null
      }
    },
    searchQuery1() {
      this.assembleQueryParam()
      this.loadData(1)
    },
    searchReset1(){
      this.queryParam = {}
      this.orderDateRange = []
      this.searchQuery1()
    },
    loadDepartTree() {
      queryDepartTreeList1().then((res) => {
        if (res.success) {
          let departList = res.result
          if (departList.length == 1 && departList[0].orgType == 1) {
            departList = departList[0].children
          }
          this.departModel.departTreeOptions = departList

          this.departModel.departTreeOptions.forEach((x) => {
            if (!x['children']) {
              x['children'] = []
            }
            let allShop = { title: '全部门店', value: '0' }
            x['children'].unshift(allShop)
          })
        }
      })
    },
    handleChange(date, dateString) {
      this.queryParam.beginTime = dateString[0]
      this.queryParam.endTime = dateString[1]
    },
    handleDetail(record){
      this.$refs.modalForm.view(record.id)
      this.$refs.modalForm.title = '返货单详情'
    },
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>